package com.wjh.rules.core.rule;

import com.wjh.rules.common.EasyStringUtils;

import javax.script.ScriptEngine;
import java.util.Map;

/**
 * @ClassName RuleFactor
 * @Description: 规则因子
 * 封装了一个表达式里面最低粒度的逻辑判断条件
 * @Author wjh
 * @Date 2020年6月19日
 */
public class RuleUnit {

    /**
     * 规则的唯一标识
     */
    private String id;

    /**
     * 规则分组标识
     */
    private String groupId;

    /**
     * 规则的脚本表达式
     */
    private String express;

    private String ruleInfo;

    /**
     * 脚本引擎
     */
    private ScriptEngine scriptEngine;

    public RuleUnit() {

    }

    public RuleUnit(String id, String groupId, String express, ScriptEngine scriptEngine, String ruleInfo) {
        this.id = id;
        this.groupId = groupId;
        this.express = express;
        this.scriptEngine = scriptEngine;
        this.ruleInfo = ruleInfo;
    }

    public boolean fire(Map<String, Object> fact,RuleUnit ru) {
        String cmd = EasyStringUtils.processTemplate(express, fact);
        ru.setExpress(cmd);
        System.out.println("-------------cmd:" + cmd + "---------------");
        try {
            boolean result = (Boolean) scriptEngine.eval(cmd);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getExpress() {
        return express;
    }

    public void setExpress(String express) {
        this.express = express;
    }

    public ScriptEngine getScriptEngine() {
        return scriptEngine;
    }

    public void setScriptEngine(ScriptEngine scriptEngine) {
        this.scriptEngine = scriptEngine;
    }

    public String getRuleInfo() {
        return ruleInfo;
    }

    public void setRuleInfo(String ruleInfo) {
        this.ruleInfo = ruleInfo;
    }

    @Override
    public String toString() {
        return "RuleUnit{" +
                "id='" + id + '\'' +
                ", groupId='" + groupId + '\'' +
                ", express='" + express + '\'' +
                ", ruleInfo='" + ruleInfo + '\'' +
                ", scriptEngine=" + scriptEngine +
                '}';
    }
}
